<template>
  <a-modal
    :title="title"
    :visible="visible"
    :confirmLoading="submitting"
    @cancel="clickCancel()"
    @ok="clickConfirm()"
    width="95%"
  >
    <!-- 行内编辑table start -->
    <!-- <span style="color: #999; font-size: 1rem;">只需配置企业自动签章的位置即可，用户签章位置无需配置，用户签章时可自己拖动。</span> -->
    <a target="_blank" href="https://open.esign.cn/tools/template-file">签章/日期位置辅助工具</a>
    <div class="title">
      <a-radio-group v-model="type" button-style="solid">
        <a-radio-button :value="1">
          企业签章配置
        </a-radio-button>
        <a-radio-button :value="2">
          个人签章配置
        </a-radio-button>

      </a-radio-group>
    </div>
    <div v-show="type == 1">
      <a-table
        bordered
        :loading="tableLoading"
        :columns="columns"
        :dataSource="data"
        :pagination="false"
        size="small"
      >
        <!--  -->
        <template
          v-for="(col, i) in ['posPage', 'posX', 'posY']"
          :slot="col"
          slot-scope="text, record"
        >
          <!-- style="margin: -5px 0" -->
          <!-- :placeholder="columns[i + 1].title" -->
          <template v-if="record.editable">
            <a-input
              v-if="record.signType == $const.SIGN_TYPES.INACTIVE.value && col == 'posPage' "
              :key="col"
              :style="{'width': '100%','visibility': record.signType == $const.SIGN_TYPES.INACTIVE.value && col== 'posX' ? 'hidden' : 'visible'}"
              :value="text"
              @change="e => handleInputStrChange(e, record.key, col)"
            />
            <a-input-number
              v-else
              :key="col"
              :style="{'width': '100%','visibility': record.signType == $const.SIGN_TYPES.INACTIVE.value && col== 'posX' ? 'hidden' : 'visible'}"
              :value="text"
              :min="1"
              :placeholder="columns[i + 1].title"
              @change="e => handleInputChange(e, record.key, col)"
            />
          </template>
          <template v-else>{{ text }}</template>
        </template>
        <template slot="signDate" slot-scope="text, record">
          <a-select style="width: 100%" :value="record.signDate" @change=" e => signDateChange(e, record.key)" :disabled="record.signType !== 1" v-if="record.editable">
            <a-select-option :value="1">需要</a-select-option>
            <a-select-option :value="0">不需要</a-select-option>
          </a-select>
          <span v-else>{{ record.datePosX ? '需要' : '不需要' }}</span>
        </template>
        <template v-for="(item, i) in ['datePosX', 'datePosY']" :slot="item" slot-scope="text,record">
          <template v-if="record.editable">
            <a-input-number
              :key="item"
              :style="{'width': '100%','visibility': record.signType == $const.SIGN_TYPES.INACTIVE.value || record.signDate == 0 ? 'hidden' : 'visible'}"
              :value="text"
              :min="1"
              :placeholder="columns[i + 5].title"
              @change="e => handleInputChange(e, record.key, item)"
            />
          </template>
          <template v-else>{{ text }}</template>
        </template>
        <template slot="operation" slot-scope="text, record">
          <span v-if="!record.editable">
            <a @click="clickEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm="clickDelete(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="clickRowSave(record)">保存</a>
            <a-divider type="vertical" />
            <a @click="clickRowCancel(record)" v-if="!record.isNew">取消</a>
            <a-popconfirm v-else title="确定删除？" ok-text="删除" cancel-text="取消" @confirm="clickDelete(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
        <template slot="signType" slot-scope="text, record">
          <span v-if="record.editable">
            <a-select :value="text" style="width:100%" @change="e => handleInputChange(e, record.key, 'signType')">
              <a-select-option v-for="item in $const.SIGN_TYPES" :key="item.value" :value="item.value" :disabled="judgeHas(item.value)">{{
                item.desc
              }}</a-select-option>
            </a-select>
          </span>
          <span v-else>
            {{ text | enumValueByKey($const.SIGN_TYPES) }}
          </span>
        </template>

      </a-table>
      <a-button block style="margin-top: 20px" type="dashed" icon="plus" @click="newRow(1)">新增签章配置</a-button>
    </div>
    <div v-show="type == 2">
      <a-table
        bordered
        :loading="tableLoading"
        :columns="personalColumns"
        :dataSource="personData"
        :pagination="false"
        size="small"
      >
        <!-- 'visibility': record.signType == $const.SIGN_TYPES.INACTIVE.value && col== 'posX' ? 'hidden' : 'visible'} -->
        <template
          v-for="(col, i) in ['posPage', 'posX', 'posY']"
          :slot="col"
          slot-scope="text, record"
        >
          <!-- style="margin: -5px 0" -->
          <a-input-number
            :key="col"
            v-if="record.editable"
            :style="{'width': '100%'}"
            :min="1"
            :value="text"
            :placeholder="personalColumns[i].title"
            @change="e => handleInputChange(e, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="signDate" slot-scope="text, record">
          <a-select style="width: 100%" :value="record.signDate" @change="e => signDateChange(e, record.key)" v-if="record.editable">
            <a-select-option :value="1">需要</a-select-option>
            <a-select-option :value="0">不需要</a-select-option>
          </a-select>
          <span v-else>{{ record.datePosX ? '需要' : '不需要' }}</span>
        </template>
        <template v-for="(item, i) in ['datePosX', 'datePosY']" :slot="item" slot-scope="text,record">
          <template v-if="record.editable">
            <a-input-number
              :key="item"
              :style="{'width': '100%','visibility': record.signType == $const.SIGN_TYPES.INACTIVE.value || record.signDate == 0 ? 'hidden' : 'visible'}"
              :value="text"
              :min="1"
              :placeholder="columns[i + 5].title"
              @change="e => handleInputChange(e, record.key, item)"
            />
          </template>
          <template v-else>{{ text }}</template>
        </template>

        <template slot="operation" slot-scope="text, record">
          <span v-if="!record.editable">
            <a @click="clickEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除？" ok-text="删除" cancel-text="取消" @confirm="clickDelete(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="clickRowSave(record)">保存</a>
            <a-divider type="vertical" />
            <a @click="clickRowCancel(record)" v-if="!record.isNew">取消</a>
            <a-popconfirm v-else title="确定删除？" ok-text="删除" cancel-text="取消" @confirm="clickDelete(record)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </template>

      </a-table>
      <a-button block style="margin-top: 20px" type="dashed" icon="plus" @click="newRow(2)">新增签章配置</a-button>
    </div>

    <!-- 行内编辑table end -->
  </a-modal>
</template>
<script>
export default {
  props: {
    visible: {
      default: false,
      type: Boolean
    },
    defaultData: {
      type: Object,
      default: () => {}
    }
  },
  components: {},
  data () {
    return {
      type: 1,
      confirmLoading: false,
      title: '自动签章配置', // 动态标题
      tableLoading: false,
      columns: [
        {
          title: '印章类型(骑缝签署仅可设置一个)',
          dataIndex: 'signType',
          key: 'signType',
          scopedSlots: { customRender: 'signType' }
        },
        {
          title: '所在页面(页码以“-”分割指定范围,“all”代表全部页码)',
          dataIndex: 'posPage',
          key: 'posPage',
          scopedSlots: { customRender: 'posPage' }
        },
        {
          title: 'X坐标',
          dataIndex: 'posX',
          key: 'posX',
          scopedSlots: { customRender: 'posX' }
        },
        {
          title: 'Y坐标',
          dataIndex: 'posY',
          key: 'posY',
          scopedSlots: { customRender: 'posY' }
        },
        {
          title: '是否需要签章日期',
          dataIndex: 'signDate',
          key: 'signDate',
          scopedSlots: { customRender: 'signDate' }
        },
        {
          title: '日期X坐标',
          dataIndex: 'datePosX',
          key: 'datePosX',
          scopedSlots: { customRender: 'datePosX' }
        },
        {
          title: '日期Y坐标',
          dataIndex: 'datePosY',
          key: 'datePosY',
          scopedSlots: { customRender: 'datePosY' }
        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      personalColumns: [
        {
          title: '所在页面',
          dataIndex: 'posPage',
          key: 'posPage',
          scopedSlots: { customRender: 'posPage' }
        },
        {
          title: 'X坐标',
          dataIndex: 'posX',
          key: 'posX',
          scopedSlots: { customRender: 'posX' }
        },
        {
          title: 'Y坐标',
          dataIndex: 'posY',
          key: 'posY',
          scopedSlots: { customRender: 'posY' }
        },
        {
          title: '是否需要签章日期',
          dataIndex: 'signDate',
          key: 'signDate',
          scopedSlots: { customRender: 'signDate' }
        },
        {
          title: '日期X坐标',
          dataIndex: 'datePosX',
          key: 'datePosX',
          scopedSlots: { customRender: 'datePosX' }
        },
        {
          title: '日期Y坐标',
          dataIndex: 'datePosY',
          key: 'datePosY',
          scopedSlots: { customRender: 'datePosY' }
        },

        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [],
      personData: [],
      // rules: {
      //   // 校验规则
      //   proId: [{ required: true, message: '请选择项目' }]
      // },
      submitting: false
    }
  },
  mounted () {},
  watch: {
    defaultData: {
      immediate: true,
      deep: true,
      handler (val) {
        if (val && val.signConfig) {
          this.type = 1
          const data = JSON.parse(val.signConfig)
          this.data = []
          this.personData = []
          if (data && data.length) {
            data.forEach(item => {
              // 给获取的数据增加一个是否需要签章日期的字段
              item.signDate = item.datePosX ? 1 : 0
              if (item.signSubject === 1) {
                this.data.push(item)
              } else {
                this.personData.push(item)
              }
            })
          }
          this.addKeyValue(this.data)
          this.addKeyValue(this.personData)
        }
      }
    }
  },
  methods: {
    // 判断是否已选骑缝
    judgeHas (value) {
      const target = this.data.find(item => item.signType === this.$const.SIGN_TYPES.INACTIVE.value)
      if (target && value === this.$const.SIGN_TYPES.INACTIVE.value) {
        return true
      } else {
        return false
      }
    },
    // 将回显的数据添加key及editable
    addKeyValue (arr) {
      arr.forEach(item => {
        item.key = Math.random().toString(36).substr(2, 10)
        item.editable = false
      })
    },
    // 新增行
    newRow (type) {
      const datas = {
        key: Math.random().toString(36).substr(2, 10),
        signSubject: type,
        roleType: type === 2 ? 1 : '',
        posPage: '',
        posX: '',
        posY: '',
        signDate: 0,
        datePosX: null,
        datePosY: null,
        signType: type === 1 ? this.$const.SIGN_TYPES.ACTIVE.value : '',
        editable: true,
        isNew: true
      }
      if (type === 1) {
        datas.posPage = datas.signType === this.$const.SIGN_TYPES.INACTIVE.value ? 'all' : ''
        this.data.push(datas)
      } else {
        this.personData.push(datas)
      }
      console.log('personData', this.personData)
    },
    // 编辑当前行
    clickEdit (row) {
      if (this.type === 1) {
        const target = this.data.find(item => item.key === row.key)
        target._originalData = { ...target }
        target.editable = true
      } else {
        const target = this.personData.find(item => item.key === row.key)
        target._originalData = { ...target }
        target.editable = true
      }

      this.$forceUpdate()
    },
    // 删除当前行
    clickDelete (row) {
      if (this.type === 1) {
        const newData = this.data.filter(item => item.key !== row.key)
        this.data = newData
      } else {
        const newData = this.personData.filter(item => item.key !== row.key)
        this.personData = newData
      }
      this.$forceUpdate()
    },
    // 保存当前行
    clickRowSave (row) {
      const { posPage, posX, posY, signType } = row
      console.log(row, '当前行')
      if (signType === this.$const.SIGN_TYPES.INACTIVE.value) {
        if ((posPage === '' || posPage === null) || (posY === '' || posY === null)) {
          this.$message.error('请将信息填写完整')
          return false
        }
      } else {
        if ((posPage === '' || posPage === null) || (posX === '' || posX === null) || (posY === '' || posY === null)) {
          this.$message.error('请将信息填写完整')
          return false
        }
      }
      if (this.type === 1) {
        const target = this.data.find(item => item.key === row.key)
        // 如果选择为骑缝 将三个坐标置空
        if (signType === this.$const.SIGN_TYPES.INACTIVE.value) {
          target.posX = null
          target.datePosX = null
          target.datePosY = null
        }
        if (target.signDate) {
          if (!target.datePosX || !target.datePosY) {
            this.$message.error('签章日期坐标为必填项')
            return false
          }
        }
        target.editable = false
        target.isNew = false
      } else {
        const target = this.personData.find(item => item.key === row.key)
        // 如果选择为不需签章 将两个坐标置空
        if (!target.signDate) {
          target.datePosX = null
          target.datePosY = null
        }
        if (target.signDate) {
          if (!target.datePosX || !target.datePosY) {
            this.$message.error('签章日期坐标为必填项')
            return false
          }
        }
        target.editable = false
        target.isNew = false
        console.log(target, '当前target')
      }
      this.$forceUpdate()
    },
    // 取消当前行编辑
    clickRowCancel (row) {
      console.log(row, '***********************')
      if (this.type === 1) {
        const target = this.data.find(item => item.key === row.key)
        Object.keys(target).forEach(key => {
          target[key] = target._originalData[key]
        })
        target.editable = false
      } else {
        const target = this.personData.find(item => item.key === row.key)
        Object.keys(target).forEach(key => {
          target[key] = target._originalData[key]
        })
        target.editable = false
      }

      this.$forceUpdate()
    },
    handleSelectChange (value) {
     console.log(this.data, '修改值', value)
    },
    handleInputStrChange (e, key, column) {
      if (this.type === 1) {
        const newData = [...this.data]
        const target = newData.find((item) => key === item.key)
        if (target) {
          console.log(e.target.value, '印章值')
          this.$set(target, column, e.target.value)
        }
      } else {
        const newData = [...this.personData]
        const target = newData.find((item) => key === item.key)
        if (target) {
          this.$set(target, column, e.target.value)
        }
      }
    },
    // input输入事件
    handleInputChange (value, key, column) {
      console.log(value, key, column, '---------')
      if (this.type === 1) {
        const newData = [...this.data]
        const target = newData.find((item) => key === item.key)
        if (target) {
          if (column === 'signType') {
            // 每次切换下拉框，选择为单页签署时将所在页码置为空,骑缝签署默认为all
            target.posPage = value === this.$const.SIGN_TYPES.INACTIVE.value ? 'all' : ''
            // 下拉框一旦改变就将签章日期置为不需要
            this.$set(target, 'signDate', 0)
          }
          this.$set(target, column, value)
          this.$forceUpdate()
        }
        console.log(target, column, value, '**************')
      } else {
        const newData = [...this.personData]
        const target = newData.find((item) => key === item.key)
        if (target) {
          this.$set(target, column, value)
        }
      }
    },
    // 签章日期下拉框改变
    signDateChange (val, key) {
      let target = null
      if (this.type === 1) {
        const newData = [...this.data]
        target = newData.find(item => key === item.key)
      } else {
        const newData = [...this.personData]
        target = newData.find(item => key === item.key)
      }
      if (target) {
        // 不需签章 日期坐标置空
        if (!val) {
          target.datePosX = null
          target.datePosY = null
        }
        target.signDate = val
        // this.$set(target, 'signDate', val)
      }
      this.$forceUpdate()
    },
    clickCancel () {
      this.data = []
      this.personData = []
      this.$emit('AllocationCancel')
    },
    clickConfirm () {
      const target = this.data.find(item => item.editable === true)
      const targetPersonal = this.personData.find(item => item.editable === true)
      if (target || targetPersonal) {
        this.$message.error('请先将每行信息进行保存再提交')
        return false
      }
      const signConfig = []
      if (this.data) {
        const checkInactiveAmount = this.data.filter(item => Number(item.signType) === 2)
        if (checkInactiveAmount.length > 1) {
          this.$message.error('骑缝章数量仅可以设置一个')
          return
        }
        this.data.forEach(item => {
          signConfig.push({
            signSubject: item.signSubject,
            roleType: item.roleType,
            signType: item.signType,
            posPage: item.posPage,
            posX: item.posX,
            posY: item.posY,
            datePosX: item.datePosX,
            datePosY: item.datePosY
          })
        })
      }
      if (this.personData) {
        this.personData.forEach(item => {
          signConfig.push({
            signSubject: item.signSubject,
            roleType: item.roleType,
            signType: item.signType,
            posPage: item.posPage,
            posX: item.posX,
            posY: item.posY,
            datePosX: item.datePosX,
            datePosY: item.datePosY
          })
        })
      }

      if (signConfig && signConfig.length) {
        this.$emit('AllocationOk', signConfig)
        // setTimeout(() => {
        //   this.data = []
        //   this.personData = []
        // }, 800)
      } else {
        this.$message.error('请添加签属配置')
        // this.data = []
        // this.personData = []
      }
    },
    clearData () {
      this.data = []
      this.personData = []
    }
  }
}
</script>
<style lang="less" scoped>
  .title{
    margin:10px 0
  }
</style>
